import User from '../User'
import {chatEvents} from './chatEvents'
import {Base64} from '../common/base64'
import EventEmitter from '../common/EventEmitter'
import {arrayInsert,arrayRemove,isMobile} from '../common/utils'
import '../common/styles/object.css'
export default class Xchat{
	constructor(chatparam) {
		if(!chatparam){
			console.error("聊天初始化参数必传!")
		}
		if(isMobile){
			console.log('================启动WEBSOCKET====================')
			return Promise.all([import('./xchatWebsocket/XchatWebsocket'),import('./xchatWebsocket/websocketProtocol')]).then(([module1,module2])=>{
				let XchatWebsocket = module1.default
				let xchat_protocol = module2.default
				chatparam = Object.assign(chatparam,{port:19288})
				this.websocket = new XchatWebsocket(chatparam,xchat_protocol)
				this.init()
				return this
			})
		}else{
			if((window.WebSocket || window.MozWebSocket) && !chatparam.openFlashSocket){
				console.log('================启动WEBSOCKET====================')
				return Promise.all([import('./xchatWebsocket/XchatWebsocket'),import('./xchatWebsocket/websocketProtocol')]).then(([module1,module2])=>{
					let XchatWebsocket = module1.default
					let xchat_protocol = module2.default
					chatparam = Object.assign(chatparam,{port:19288})
					this.websocket = new XchatWebsocket(chatparam,xchat_protocol)
					this.init()
					return this
				})
			}else{
				console.log('================启动FLASH SOCKET====================')
				return import('./xchatFlashsocket/XchatSwf').then(({default:XchatSwf})=>{
					chatparam = Object.assign(chatparam,{port:19188})
					if(document.getElementById('xchat')){
						document.getElementById('xchat').parentNode.removeChild(document.getElementById('xchat'))
					}
					let flashSocketWrap = '<div id="xchat"></div>'
					document.body.insertAdjacentHTML('beforeEnd', flashSocketWrap)
					this.websocket = new XchatSwf(chatparam,'xchat')
					this.init()
					return this
				})
			}
		}
	}
	init(){
		this.chatEvents = chatEvents
		//房间所有人员的hash表
		this.members = {} 
		//房间私聊成员数组
		this.private_chat_array = []
		//被选中uid
		this.selected_uid = 0
		//房间总人数
		this.member_count = 0 
		this.emitter = new EventEmitter()
		this.onmessage()
	}
	onmessage(){
		this.websocket.on(chatEvents.MSG_LOGIN_ACK,(packet_object)=>{
			this.emitter.trigger(chatEvents.MSG_LOGIN_ACK,packet_object)
		})
		this.websocket.on(chatEvents.MSG_REENTER,(packet_object)=>{
			this.emitter.trigger(chatEvents.MSG_REENTER,packet_object)
		})
		this.websocket.on(chatEvents.MSG_SESSION_PARAM,(packet_object)=>{
			this.emitter.trigger(chatEvents.MSG_SESSION_PARAM,packet_object)
		})
		this.websocket.on(chatEvents.MSG_USER_LIST_PRE,(packet_object)=>{
			if(Array.prototype.isPrototypeOf(packet_object)){
				for(let item of packet_object){
					if(typeof(item) === 'object'){
						this.websocket.emitter.trigger(chatEvents.MSG_SOMEBODY_IN,item)
					}
				}
			}
		})
		this.websocket.on(chatEvents.MSG_SOMEBODY_IN,(packet_object)=>{
			packet_object.appdata = JSON.parse(Base64.decode(packet_object.appdata))
			packet_object.appdata.nickname = Base64.decode(packet_object.appdata.nickname_b64)
			packet_object.appdata.in_out_hint = packet_object.in_out_hint
			let user = new User(packet_object)
			this.userIn(user)
			this.emitter.trigger(chatEvents.MSG_SOMEBODY_IN,{appdata:packet_object.appdata,private_chat_array:this.private_chat_array})
		})
		this.websocket.on(chatEvents.MSG_SOMEBODY_OUT,(packet_object)=>{
			let u = this.getUser(packet_object.uid)
			this.userOut(packet_object.uid)
			this.emitter.trigger(chatEvents.MSG_SOMEBODY_OUT,{param:packet_object,private_chat_array:this.private_chat_array})
		})
		this.websocket.on(chatEvents.MSG_SOMEBODY_CHANGELEVEL,(packet_object)=>{
			let u = this.getUser(packet_object.uid)
			let appdata = u.appdata
			this.userOut(packet_object.uid)
			appdata.nickname = Base64.decode(u.appdata.nickname_b64)
			appdata.levelinroom = packet_object.level
			packet_object.appdata = appdata
			let user = new User(packet_object)
			this.userIn(user)
			this.emitter.trigger(chatEvents.MSG_SOMEBODY_CHANGELEVEL,{param:packet_object,private_chat_array:this.private_chat_array})
		})
		this.websocket.on(chatEvents.MSG_SOMEBODY_CHANGEAPPDATA,(packet_object)=>{
			let appdata = JSON.parse(Base64.decode(packet_object.appdata))
			this.userOut(packet_object.uid)
			appdata.nickname = Base64.decode(appdata.nickname_b64)
			packet_object.appdata = appdata
			let user = new User(packet_object)
			this.userIn(user)
			this.emitter.trigger(chatEvents.MSG_SOMEBODY_CHANGEAPPDATA,{param:packet_object,private_chat_array:this.private_chat_array})
		})
		this.websocket.on(chatEvents.MSG_SOMEBODY_CHATENABLE,(packet_object)=>{
			this.emitter.trigger(chatEvents.MSG_SOMEBODY_CHATENABLE,packet_object)
		})
		this.websocket.on(chatEvents.MSG_KICKOUT,(packet_object)=>{
			this.emitter.trigger(chatEvents.MSG_KICKOUT,packet_object)
		})
		this.websocket.on(chatEvents.MSG_ROOMCLEAR,(packet_object)=>{
			this.emitter.trigger(chatEvents.MSG_ROOMCLEAR,packet_object)
		})
		this.websocket.on(chatEvents.MSG_ROOMHOT,(packet_object)=>{
			this.emitter.trigger(chatEvents.MSG_ROOMHOT,packet_object)
		})
		this.websocket.on(chatEvents.MSG_MESSAGE,(packet_object)=>{
			let chatdata = JSON.parse(Base64.decode(packet_object.chatdata))
			this.emitter.trigger(chatEvents.MSG_MESSAGE,chatdata)
		})
		this.websocket.on(chatEvents.MSG_TOKEN_SETTING,(packet_object)=>{
			this.emitter.trigger(chatEvents.MSG_TOKEN_SETTING,packet_object)
		})
		this.websocket.on(chatEvents.MSG_TOKEN_TIMER,(packet_object)=>{
			this.emitter.trigger(chatEvents.MSG_TOKEN_TIMER,packet_object)
		})
		this.websocket.on(chatEvents.MSG_TOKEN_INFO,(packet_object)=>{
			this.emitter.trigger(chatEvents.MSG_TOKEN_INFO,packet_object)
		})
		this.websocket.on(chatEvents.MSG_TOKEN_REQUEST,(packet_object)=>{
			this.emitter.trigger(chatEvents.MSG_TOKEN_REQUEST,packet_object)
		})
		this.websocket.on(chatEvents.MSG_ROOM_REINIT,(packet_object)=>{
			this.emitter.trigger(chatEvents.MSG_ROOM_REINIT,packet_object)
		})
		this.websocket.on(chatEvents.MSG_TOKEN_ADJUST,(packet_object)=>{
			this.emitter.trigger(chatEvents.MSG_TOKEN_ADJUST,packet_object)
		})
		this.websocket.on(chatEvents.MSG_SOCKET_ERROR,()=>{
			this.emitter.trigger(chatEvents.MSG_SOCKET_ERROR)
		})
	}
	getUser(uid){
		if (uid in this.members){
			return this.members[uid];
		}
		return null;
	}
	getSelectedUser(){
		if (this.selected_uid == 0){
			return null;
		}
		return this.members[this.selected_uid];
	}
	userSelected(uid){
		this.selected_uid = uid;
	}
	userIn(user){
		console.log('UserIn:'+user.appdata.nickname);
		//去重
		this.userOut(user.uid);
		
		this.members[user.uid] = user;
		var before_u = null;
		var arrayLength = this.private_chat_array.length;
		if(((arrayLength<100 && user.rank>=111) || user.levelinroom>=500) && user.level !== 6000){
			for(var i=0;i<this.private_chat_array.length;i++){
				var u = this.private_chat_array[i];
				if(user.rank > u.rank || (user.rank == u.rank && user.appdata.nicegid < u.appdata.nicegid)){
					before_u = u;
					arrayInsert(this.private_chat_array,i,user);
					break;
				}
			}
			if(before_u === null){
				this.private_chat_array.push(user);
			}
		}
		if (user.level != 6000){
			this.member_count += 1;
		}
	}
	userOut(uid){
		let user = this.getUser(uid);
		if(!user){
			return
		}
		let privateIndex = this.private_chat_array.findIndex((item)=>item.uid === uid)
		if(privateIndex !== -1){
			arrayRemove(this.private_chat_array,privateIndex)
		}
		if (user.level != 6000 && this.member_count>0){
			this.member_count -= 1
		}
		delete this.members[uid]
	}
	clear(){
		this.members = {}
		this.private_chat_array = []
	}
	on(event, listener) {
		this.emitter.on(event, listener)
	}
	off(event, listener) {
		this.emitter.off(event, listener)
	}
}